
<template>
  <div style="margin-top: 10px;" class="wrap">
    <el-form ref="form" :model="form" :rules="rules" label-width="100px"
             @submit.native.prevent>
      <el-form-item label="事件类型:" prop="type">
        <el-select v-model="form.type" class="ele-block" clearable placeholder="请选择事件类型" :disabled="typeFlag">
          <el-option
            v-for="(item, index) in typeList"
            :key="index"
            :label="item"
            :value="item"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="故障现象:"  v-if="form.type === '客户报修'">
        <el-input v-model="form.description" placeholder="请输入故障现象" type="textarea" :disabled="!typeFlag"/>
      </el-form-item>
      <el-form-item label="情况说明:"  v-if="form.type !== '客户报修'">
        <el-input v-model="form.description" placeholder="请输入情况说明" type="textarea" :disabled="!typeFlag"/>
      </el-form-item>

      <el-form-item label="客户:" prop="customer_name">
        <el-autocomplete v-model="form.customer_name" :fetch-suggestions="querySearchAsync" class="w-full"
                         placeholder="搜索客户" value-key="name" @select="handleSelect" clearable
                         :disabled="!typeFlag"
                         @clear="clearCustomer"></el-autocomplete>
      </el-form-item>

      <el-form-item label="联系人:" prop="contact_name">
        <div style="display: flex;justify-content: space-between" class="contact_nameWrap">
          <el-select
            :disabled="!this.form.customer_name"
            @focus="focus"
            v-model="form.contact_name"
            remote
            filterable
            blur
            @change="changeContact"
            :remote-method="querySearchContact_name"
            clearable
            @clear="clearCustomer"
            value-key="id"
            placeholder="请输先选择客户"
            :loading="contactLoading">
            <el-option
              blur
              v-for="item in contact_nameList"
              :key="item.id"
              :label="item.name"
              :value="item.id+'-'+item.name+'-'+item.phone">
              <template #default>
                {{ item.name }}
                联系人: <span style="margin-right: 14px;">{{ item.name ? item.name : '无' }}</span>
                联系电话: <span style="margin-right: 14px;">{{ item.phone ? item.phone : '无' }}</span>
              </template>
            </el-option>
          </el-select>


          <el-button style="margin-left: 10px" type="primary" @click="addCustomerUser" :disabled="!form.customer_id">
            新建
          </el-button>
        </div>
      </el-form-item>

      <el-form-item label="联系电话:" prop="contact_telephone">
        <el-input
          disabled
          v-model="form.contact_telephone"
          clearable
          placeholder=""/>
      </el-form-item>

      <el-form-item label="所属区域:" prop="areas">
        <div class="area">
          <City @areaChange="areaChange" :ids="cityName" ref="city" :disabled="!typeFlag"/>
        </div>
      </el-form-item>
      <el-form-item label="详细地址:" prop="address">
        <el-input
          :disabled="!typeFlag"
          v-model="form.address"
          clearable
          placeholder=""/>
      </el-form-item>

      <el-form-item label="产品:" prop="product_id" v-if="form.type === '客户报修'">
        <div style="display: flex;justify-content: space-between" class="contact_nameWrap">
          <el-select
            :disabled="!this.form.customer_name"
            @focus="focus"
            v-model="form.product_id"
            remote
            filterable
            blur
            :remote-method="querySearchProduct"
            clearable
            value-key="id"
            :placeholder="!this.form.customer_name?'请输先选择客户':'请输入出厂编号'"
            :loading="productLoading">
            <el-option
              blur
              v-for="item in productList"
              :key="item.id"
              :label="item.name"
              :value="item.id">
              <template #default>
                出厂编号: <span style="margin-right: 14px;">{{ item.name ? item.name : '无' }}</span>
<!--                编号: <span style="margin-right: 14px;">{{ item.product_number ? item.product_number : '无' }}</span>-->
              </template>
            </el-option>
          </el-select>
          <el-button style="margin-left: 10px" type="primary" @click="addProduct" :disabled="!form.customer_id">新建
          </el-button>
        </div>

      </el-form-item>
      <el-form-item v-if="form.type === '客户报修'" label="照片" prop="attachment">
        <uploadImage v-model="form.images" :limit="4"></uploadImage>
        <div class="el-upload__tip">请上传jpg、png图片附件，最多可上传4张，单张大小不要超过8M。</div>
      </el-form-item>

            <el-form-item label="负责人:" prop="user_id">
              <el-select filterable  remote v-model="form.userName" @focus.prevent="appoint" clearable
                         placeholder="请选择负责人"/>
            </el-form-item>

    </el-form>
    <div slot="footer" style="display: flex;justify-content: center">
      <el-button @click="updateVisible(false)">取消</el-button>
      <el-button
        :loading="loading"
        type="primary"
        @click="save">保存
      </el-button>
    </div>
    <addContact
      ref="AddConcat"
      :visible.sync="showCustomerUserEdit"
      @done="reset"
    />
    <productForm
      ref="productFormRef"
      :customerId="customer_id"
      :customerName="customer_name"
      :visible.sync="showProductEdit"
      @done="resetProduct"/>
    <Appoint @certainUser="certainUser" v-model="form.assistUserName" ref="Appoint" />
  </div>
</template>

<script>
import addContact from "@/views/workTickets/workTickets/addWorkTicket/compoments/addContact.vue";
import productForm from '@/views/workTickets/workTickets/addWorkTicket/compoments/product-form.vue'
import uploadImage from '@/components/uploadImage.vue'
import City from '@/components/city'
import Appoint from '../event/components/Appoint'

import {removePageTab} from '@/utils/page-tab-util'


export default {
  components: {addContact, uploadImage, City, productForm,Appoint},
  props: {},
  data() {
    const validateAreas = (rule, value, callback) => {
      // 判断 country_id province_id city_id county_id 是否为空
      if (!this.city.length) {
        callback(new Error("请选择地区"));
      } else {
        callback();
      }
    };
    const validateContact_name = (rule, value, callback) => {
      if (!this.form.contact_name) {
        callback(new Error("选择联系人"));
      } else {
        callback();
      }
    };
    const validateCustomer_name = (rule, value, callback) => {
      if (!this.form.contact_name) {
        callback(new Error("选择客户"));
      } else {
        callback();
      }
    };
    const validateContact_phone = (rule, value, callback) => {
      if (!this.form.contact_telephone) {
        callback(new Error("请输入联系电话"));
      } else {
        callback();
      }
    };
    const validateAddress = (rule, value, callback) => {
      if (!this.form.address) {
        callback(new Error("请输入详细地址"));
      } else {
        callback();
      }
    };
    const validateProduct_ids = (rule, value, callback) => {
      if (!this.form.address) {
        callback(new Error("请选择产品"));
      } else {
        callback();
      }
    };
    const validateType = (rule, value, callback) => {
      if (!this.form.type) {
        callback(new Error("请选择工单类型"));
      } else {
        callback();
      }
    };
    const validateUser_id = (rule, value, callback) => {
      // 判断 country_id province_id city_id county_id 是否为空
      if (!this.form.userName) {
        callback(new Error("请选择负责人"));
      } else {
        callback();
      }
    }

    return {
      contactLoading:false,
      //新增产品
      showProductEdit: false,
      //回显数据
      cityName: '',
      //新增联系人
      showCustomerUserEdit: false,
      //客户标签数组
      tag_nameList: [
        "重要",
        "普通",
        "一般",
        "较低",
      ],
      //产品远程搜索加载
      productLoading: false,
      //多选产品
      productList: [],
      // 上传照片
      attachmentUrl: [],
      // 选中的省市区
      city: [],
      // 选中的省市
      provinceCity: [],
      // 选中的省
      province: [],
      //客户类型数组
      typeList: [
        "维保工单",
        "调试工单",
        "安装工单",
        "培训工单"
      ],
      deptLists: [],
      rules: {
        service_content: [
          {required: true, message: "请选择服务内容", trigger: "change"}
        ],
        plan_at: [
          {required: true, message: "请选择计划时间", trigger: "change"}
        ],
        customer_name: [
          {required: true, validator: validateCustomer_name, trigger: "change"}
        ],

        contact_name: [
          {required: true, validator: validateContact_name, trigger: "change"}
        ],
        contact_telephone: [
          {required: true, validator: validateContact_phone, trigger: "blur"}
        ],
        level: [
          {required: true, message: "请选择优先级", trigger: "change"}
        ],
        areas: [
          {required: true, trigger: "change", validator: validateAreas}
        ],
        product_ids: [
          {required: true, validator: validateProduct_ids, trigger: "blur"}
        ],
        address: [
          {required: true, validator: validateAddress, trigger: "blur"}
        ],


        type: [
          {required: true, validator: validateType, trigger: "blur"}
        ],
                user_id: [
                  {required: true, validator: validateUser_id, trigger: "change"}
               ],
      },
      //组件激活
      key: null,
      //联系人
      contact_nameList: [],
      //客户id 名称
      customer_name: null,
      customer_id: null,
      //服务内容
      serviceContentList: [],
      //服务类型
      serviceTypeList: [],
      //表单数组配置项
      dataList: [],
      // 表单数据
      form: {
        images: [],
        description: '',
        address: '',
        customer_name: '',
        contact_telephone: '',
      },
      // 提交状态
      loading: false,
      // 是否是修改
      isUpdate: false,
      //类型是否可选
      typeFlag: true,
      eventData: {},
    };
  },
  watch: {
    data() {
      this.isUpdate = !!(this.data && this.data.id);
    }
  },
  mounted() {
    //如果存就是事件转工单
    if (this.$route.query.event_number) {
      this.typeFlag = false
      //将事件的数据带到工单
      this.eventData = this.$route.query
      this.form.event_id = this.eventData.id
      this.form.description = this.eventData.description
      this.form.contact_name = this.eventData.contact_name
      this.form.contact_telephone = this.eventData.contact_telephone
      this.form.address = this.eventData.address
      this.form.customer_name = this.eventData.customer_name
      this.form.customer_id = this.eventData.customer_id
      this.city = [this.eventData.province_id, this.eventData.city_id, this.eventData.county_id]
      if (this.eventData.product_id * 1 !== 0) {
        this.form.product_id = this.eventData.product_id
        this.form.product_ids.push(this.eventData.name)
      }
      this.$nextTick(() => {
        this.$refs.city.addressIds = this.eventData.province_name + '/' + this.eventData.city_name + '/' + this.eventData.county_name
      })
    } else {
      this.form.type = this.$route.query.type
      this.$forceUpdate()
    }
  },
  methods: {
    //远程搜索联系人
    querySearchContact_name(query){
        this.productLoading = true;
        this.$http.get(`/customers/${this.form.customer_id}/users?limit=10&name=${query}`,).then((res) => {
          this.productLoading = false;
          this.contact_nameList = res.data.data
        }).catch(e => {
          this.$message.error(e.message);
        });
    },
    //修改联系人
    changeContact(val){
      console.log(val)
      this.form.contact_name=val.split('-')[1]
      this.form.customer_user_id=val.split('-')[0]
      this.form.contact_telephone =val.split('-')[2]
      this.$forceUpdate()
    },
    certainUser(user) {
      this.$refs.Appoint.visible = false
      this.form.userName = user.realname
      this.$forceUpdate()
      this.form.user_id = user.id
    },
    appoint() {
      this.$refs.Appoint.visible = true;
      this.$refs.Appoint.isCollaborator = false;
    },
    //新建产品
    addProduct() {
      console.log(this.eventData,this.form)
      this.$refs.productFormRef.showDialog("add", this.eventData.city_name ? this.eventData : this.form);
    },
    //清除客户
    clearCustomer() {
      this.form.product_id = []
      this.contact_nameList = []
      this.$refs.city.addressIds = ''
      this.form.contact_name = ''
      this.form.contact_telephone = ''
      this.customer_user_id=''
      this.form.address = ''
      this.$forceUpdate()
    },
    areaChange(val) {
      this.city = val
    },
    focus() {
      this.querySearchProduct('')
    },
    //新增联系人
    addCustomerUser() {
      this.$refs.AddConcat.form.customer_id=this.form.customer_id
      this.$refs.AddConcat.form.customer_name=this.form.customer_name
      this.showCustomerUserEdit = true

    },
    //添加联系人之后
    reset(res) {
      this.form.contact_telephone = res.phone
      this.form.customer_user_id=res.id
      this.form.contact_name = res.name
      this.$forceUpdate()
    },
    //添加产品之后
    resetProduct(res) {
      this.form.product_id = res.id
      this.form.product_ids.push(res.id)
    },
    //远程搜索产品
    querySearchProduct(query) {
      this.productLoading = true;
      this.$http.get(`/customers/${this.form.customer_id}/products?limit=10&name=${query}`,).then((res) => {
        this.productLoading = false;
        this.productList = res.data.data
      }).catch(e => {
        this.$message.error(e.message);
      });
    },
    querySearchAsync(query, cb) {
      if (query == '') {
        this.city = []
        this.form.contact_name = ''
        this.form.contact_telephone = ''
        this.customer_user_id=''
        this.form.address = ''
      }
      query = query ? query : ''
      this.$http.get(`/customers?page=1&limit=10`, {params: {keyword: query}}).then((res) => {
        cb(res.data.data)
      }).catch(e => {
        this.$message.error(e.message);
      });
    },
    //选择客户
    handleSelect(item) {
      this.form.product_ids = []
      this.form.customer_id = item.id
      this.customer_id = item.id
      this.contact_nameList = []
      let defaultConcat = null
      this.city = [item.province_id, item.city_id, item.county_id]
      this.form.province_id = item.province_id
      this.form.city_id = item.city_id
      this.form.county_id = item.county_id
      this.form.province_name = item.province_name
      this.form.city_name = item.city_name
      this.form.county_name = item.county_name
      this.cityName = item.province_name + '/' + item.city_name + '/' + item.county_name
      this.$refs.city.addressIds = this.cityName
      this.$forceUpdate();
      this.form.address = item.address
      if (item.users.length != 0) {
        this.contact_nameList = item.users.map((item) => {
          return {name: item.name, phone: item.phone,id:item.id}
        })
        //选择客户之后渲染默认联系人
        defaultConcat = item.users.filter(item => item.is_default = true)[0]
        this.form.contact_telephone = defaultConcat.phone
        this.form.customer_user_id=defaultConcat.id
        this.form.contact_name = defaultConcat.name

      } else {
        this.form.customer_user_id=''
        this.form.contact_telephone = ''
        this.form.contact_name = ''
      }
      if (defaultConcat) {
        this.customer_user_id = item.id
        this.contact_name = item.name
      }
    },
    /* 保存编辑 */
    save() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.form = Object.assign({}, this.form, {
            province_id: this.city[0],
            city_id: this.city[1],
            county_id: this.city[2]
          });
          this.loading = true;
          this.$http.post(`/events`,
            Object.assign({}, this.form, {})
          ).then(res => {
            this.loading = false;
            if (res.data.code === 0) {
              removePageTab('/event/addEvent')
              this.$router.push({path: '/event/event'})
            } else {
              this.$message.error(res.data.msg);
            }
          }).catch(e => {
            this.loading = false;
            this.$message.error(e.message);
          });
          // }

        } else {
          return false;
        }
      });
    },
    /* 更新visible */
    updateVisible(value) {
      this.city = []
      this.form = {}
      this.$emit('update:visible', value);
      this.$emit('reload');
      this.$router.push({path: '/event/event'})
    },
    /* 初始化form数据 */
    initFormData(data) {
      // 初始化默认值
      let form = {level: 1};
      if (data) {
        this.city = [data.province_id, data.city_id, data.county_id]
        this.form = data
        Object.assign(form, data, {
          pid: data.pid === 0 ? null : data.pid,
        });
      }
      return form;
    },
  }
}
</script>

<style scoped>
.area /deep/.el-cascader{
  width: 100%;
}
/deep/ .el-select{
  width: 100%;
}
.el-autocomplete {
  width: 100%;
}

.el-input {
  width: 100% !important;
}

.wrap {
  margin: 0 auto;
  width: 50%;
  padding-top: 30px;
}

.ele-admin-body {
  background: #fff;
}
</style>
